package com.castle.fortress.admin.rule.list.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.castle.fortress.admin.rule.rule.entity.RuleEntity;
import com.castle.fortress.admin.rule.rule.service.RuleService;
import com.castle.fortress.admin.rule.list.dto.RuleListDto;
import com.castle.fortress.admin.rule.list.entity.RuleListEntity;
import com.castle.fortress.admin.rule.list.mapper.RuleListMapper;
import com.castle.fortress.admin.rule.list.service.RuleListService;
import com.castle.fortress.admin.rule.listRule.entity.RuleListRuleEntity;
import com.castle.fortress.admin.rule.listRule.service.RuleListRuleService;
import com.castle.fortress.admin.utils.Sequence;
import com.castle.fortress.common.utils.ConvertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 规则清单信息表 服务实现类
 *
 * @author
 * @since 2025-04-22
 */
@Service
public class RuleListServiceImpl extends ServiceImpl<RuleListMapper, RuleListEntity> implements RuleListService {

    @Autowired
    private RuleListRuleService ruleListRuleService;

    @Autowired
    private RuleService ruleService;

    /**
    * 获取查询条件
    * @param ruleListDto
    * @return
    */
    public QueryWrapper<RuleListEntity> getWrapper(RuleListDto ruleListDto){
        QueryWrapper<RuleListEntity> wrapper= new QueryWrapper();
        if(ruleListDto != null){
            RuleListEntity ruleListEntity = ConvertUtil.transformObj(ruleListDto,RuleListEntity.class);
            wrapper.like(ruleListEntity.getId() != null,"id",ruleListEntity.getId());
            wrapper.like(StrUtil.isNotEmpty(ruleListEntity.getListName()),"list_name",ruleListEntity.getListName());
            wrapper.like(StrUtil.isNotEmpty(ruleListEntity.getListBrief()),"list_brief",ruleListEntity.getListBrief());
            wrapper.like(ruleListEntity.getCreateTime() != null,"create_time",ruleListEntity.getCreateTime());
            wrapper.like(ruleListEntity.getUpdateTime() != null,"update_time",ruleListEntity.getUpdateTime());
            wrapper.like(ruleListEntity.getCreateUser() != null,"create_user",ruleListEntity.getCreateUser());
            wrapper.like(ruleListEntity.getUpdateUser() != null,"update_user",ruleListEntity.getUpdateUser());
			wrapper.eq(ruleListEntity.getIsDeleted() != null,"is_deleted",ruleListEntity.getIsDeleted());
        }
        return wrapper;
    }


    @Override
    public IPage<RuleListDto> pageRuleList(Page<RuleListDto> page, RuleListDto ruleListDto) {
        // 计算偏移量
        int offset = (int) ((page.getCurrent() - 1) * page.getSize());
        int limit = (int) page.getSize();

        // 查询总记录数
        Long total = baseMapper.selectPageCount(ruleListDto);

        // 查询分页数据
        List<RuleListEntity> records = baseMapper.selectPageList(ruleListDto, offset, limit);

        // 转换结果
        Page<RuleListDto> resultPage = new Page<>(page.getCurrent(), page.getSize(), total);
        resultPage.setRecords(ConvertUtil.transformObjList(records, RuleListDto.class));

        return resultPage;
    }


    @Override
    public List<RuleListDto> listRuleList(RuleListDto ruleListDto){
        QueryWrapper<RuleListEntity> wrapper = getWrapper(ruleListDto);
        List<RuleListEntity> list = baseMapper.selectList(wrapper);
        return ConvertUtil.transformObjList(list,RuleListDto.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveRuleListWithRules(RuleListDto ruleListDto) {
        // 保存规则清单
        RuleListEntity ruleListEntity = ConvertUtil.transformObj(ruleListDto, RuleListEntity.class);
        ruleListEntity.setCreateTime(new Date());
        ruleListEntity.setUpdateTime(new Date());
        ruleListEntity.setIsDeleted(2);
        ruleListEntity.setId(Sequence.getInstance().nextId());
        boolean success = this.save(ruleListEntity);

        if (success && ruleListDto.getRuleList() != null && !ruleListDto.getRuleList().isEmpty()) {
            // 保存规则关联关系
            List<RuleListRuleEntity> ruleListRules = ruleListDto.getRuleList().stream()
                .map(ruleId -> {
                    RuleListRuleEntity ruleListRule = new RuleListRuleEntity();
                    ruleListRule.setId(Sequence.getInstance().nextId());
                    ruleListRule.setListId(ruleListEntity.getId());
                    ruleListRule.setRuleId(ruleId);
                    ruleListRule.setCreateTime(new Date());
                    ruleListRule.setCreateUser(ruleListDto.getCreateUser());
                    ruleListRule.setIsDeleted(2);
                    return ruleListRule;
                })
                .collect(Collectors.toList());

            success = ruleListRuleService.saveBatch(ruleListRules);
        }

        return success;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateRuleListWithRules(RuleListDto ruleListDto) {
        // 更新规则清单
        RuleListEntity ruleListEntity = ConvertUtil.transformObj(ruleListDto, RuleListEntity.class);
        boolean success = this.updateById(ruleListEntity);

        if (success && ruleListDto.getRuleList() != null) {
            // 删除旧的关联关系
            QueryWrapper<RuleListRuleEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("list_id", ruleListDto.getId())
                  .eq("is_deleted", 2);
            ruleListRuleService.remove(wrapper);

            if (!ruleListDto.getRuleList().isEmpty()) {
                // 保存新的关联关系
                List<RuleListRuleEntity> ruleListRules = ruleListDto.getRuleList().stream()
                    .map(ruleId -> {
                        RuleListRuleEntity ruleListRule = new RuleListRuleEntity();
                        ruleListRule.setId(Sequence.getInstance().nextId());
                        ruleListRule.setListId(ruleListDto.getId());
                        ruleListRule.setRuleId(ruleId);
                        ruleListRule.setCreateTime(new Date());
                        ruleListRule.setCreateUser(ruleListDto.getUpdateUser());
                        ruleListRule.setIsDeleted(2);
                        return ruleListRule;
                    })
                    .collect(Collectors.toList());

                success = ruleListRuleService.saveBatch(ruleListRules);
            }
        }

        return success;
    }

    @Override
    public RuleListDto getRuleListDetail(Long id) {
        // 获取规则清单基本信息
        RuleListEntity ruleListEntity = this.getById(id);
        if (ruleListEntity == null) {
            return null;
        }

        // 转换为DTO
        RuleListDto ruleListDto = ConvertUtil.transformObj(ruleListEntity, RuleListDto.class);

        // 获取关联的规则ID列表
        QueryWrapper<RuleListRuleEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("list_id", id)
              .eq("is_deleted", 2);
        List<RuleListRuleEntity> ruleListRules = ruleListRuleService.list(wrapper);

        if (ruleListRules != null && !ruleListRules.isEmpty()) {
            // 设置规则ID列表
            List<Long> ruleIds = ruleListRules.stream()
                .map(RuleListRuleEntity::getRuleId)
                .collect(Collectors.toList());
            ruleListDto.setRuleList(ruleIds);

            // 设置规则数量
            ruleListDto.setCount(ruleIds.size());

            // 获取规则详情列表
            List<RuleEntity> rules = ruleService.listByIds(ruleIds);
            ruleListDto.setRules(rules);
        } else {
            ruleListDto.setRuleList(new ArrayList<>());
            ruleListDto.setCount(0);
            ruleListDto.setRules(new ArrayList<>());
        }

        return ruleListDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteRuleListWithRules(Long id) {
        if (id == null) {
            return false;
        }

        // 删除规则清单与规则的关联关系
        QueryWrapper<RuleListRuleEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("list_id", id)
                .eq("is_deleted", 2);
        ruleListRuleService.remove(wrapper);

        // 删除规则清单
        return this.removeById(id);
    }

}

